from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db import transaction
from .models import TestSuite, TestCase, TestExecution
from .serializers import TestSuiteSerializer, TestCaseSerializer, TestExecutionSerializer


class TestSuiteViewSet(viewsets.ModelViewSet):
    queryset = TestSuite.objects.all()
    serializer_class = TestSuiteSerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @action(detail=True, methods=['get'])
    def test_cases(self, request, pk=None):
        """获取套件下的所有测试用例"""
        suite = self.get_object()
        test_cases = suite.testcase_set.all()
        serializer = TestCaseSerializer(test_cases, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def execute(self, request, pk=None):
        """执行UI测试套件"""
        suite = self.get_object()

        # 创建执行记录
        execution = TestExecution.objects.create(
            suite=suite,
            executed_by=request.user,
            total_cases=suite.testcase_set.count()
        )

        # 这里可以调用你的UI测试执行引擎
        # 暂时模拟执行
        execution.status = 'success'
        execution.passed_cases = suite.testcase_set.count()
        execution.failed_cases = 0
        execution.execution_log = f"UI测试套件 {suite.name} 执行完成"
        execution.save()

        execution_serializer = TestExecutionSerializer(execution)
        return Response(execution_serializer.data)


class TestCaseViewSet(viewsets.ModelViewSet):
    queryset = TestCase.objects.all()
    serializer_class = TestCaseSerializer

    def get_queryset(self):
        queryset = TestCase.objects.all()
        suite_id = self.request.query_params.get('suite_id')
        if suite_id:
            queryset = queryset.filter(suite_id=suite_id)
        return queryset


class TestExecutionViewSet(viewsets.ModelViewSet):
    queryset = TestExecution.objects.all()
    serializer_class = TestExecutionSerializer

    def perform_create(self, serializer):
        serializer.save(executed_by=self.request.user)